package com.example.martian.utils;

import com.alibaba.fastjson.JSONArray;
import com.example.martian.config.util.RedisUtils;
import com.example.martian.mapper.IndexMapper;
import com.example.martian.mapper.RedPacketMapper;
import com.example.martian.service.TaskRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.DefaultApplicationArguments;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class HongBaoUtils {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private IndexMapper indexMapper;

    @Autowired
    private RedPacketMapper redPacketMapper;

    @Autowired
    private ExchangeRateUtils exchangeRateUtils;

    @Autowired
    private TaskRunner runner;

    public List<Double> hongbao(double amount, int num, double min){
        List<Double> list = new ArrayList<>();
        for (int i = 1;i < num;i++){
            double dafeAmount = (amount - (num - i)*min) / (num - i);
            double money = Math.random()*(dafeAmount - min) + min;
            BigDecimal money_bd = new BigDecimal(money);
            money = money_bd.setScale(8,BigDecimal.ROUND_HALF_UP).doubleValue();
            amount = amount - money;
            BigDecimal dbAmount = new BigDecimal(amount);
            amount = dbAmount.setScale(8,BigDecimal.ROUND_HALF_UP).doubleValue();
            list.add(money);
        }
        list.add(amount);
        System.out.println(list);
        return list;
    }

    public Object robHongbaoUtil(String cipher,String address,String accountUid){
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        JSONArray jsonArray = new JSONArray();
        Map<String, Object> map1 = null;
        Map<String, Object> map = null;
        Map<String,Object> objMap = null;
        boolean exists = redisUtils.exists(cipher);
        boolean b = redisUtils.exists(cipher + address);
        if (b){
            return Utils.toJSON("您已抢过该红包",Utils.toJSONmap(),"2");
        }
        if (!exists){
            return Utils.toJSON("没有匹配的红包",Utils.toJSONmap(),"1");
        }else {
            List<Map<String,Object>> mapList = redisUtils.getCacheListInMap(cipher);
            if (mapList.size() == 0){
                return Utils.toJSON("该红包已抢完",Utils.toJSONmap(),"3");
            }
            //随机获取一个集合当中的索引编号
            int index = new Random().nextInt(mapList.size());
            for (int i = 0;i < mapList.size();i++){
                if (i == index){
                    map = mapList.get(i);
                    mapList.remove(i);
                }
            }
            Object money = map.get("sendMoney");
            String coin = map.get("coin").toString();
            List<Map<String,Object>> list = new ArrayList<>();
            for (Map<String,Object> objectMap : mapList){
                map1 = new HashMap<>();
                map1.put("value", objectMap.get("value"));
                map1.put("coin", objectMap.get("coin"));
                map1.put("number",objectMap.get("number"));
                map1.put("invitationcode",objectMap.get("invitationcode"));
                map1.put("address",objectMap.get("address"));
                map1.put("sendMoney",money);
                map1.put("addressUid",objectMap.get("addressUid"));
                list.add(map1);
            }
            BigDecimal sendMoney = new BigDecimal(map.get("value").toString());
            String moneyCoin = indexMapper.selectMoneyByCoin(coin, address);
            //计算红包收益
            String add = BigDecimalUtils.add(moneyCoin, sendMoney.toString(), 8);
            redPacketMapper.updateCoinMoney(address,coin,add);
            redisUtils.setCacheListInMap(cipher,list);
            //抢到的红包存入缓存，以免重复抢
            redisUtils.setDataToCache(cipher+address,cipher,24*60*60*1000);
            map.put("createTime",dateFormat.format(date));
            map.put("remainNumber",mapList.size());
            map.put("accountUid",accountUid);
            String addressUid = map.get("addressUid").toString();
            Integer number = Integer.valueOf(map.get("number").toString());
            Integer remainNumber = Integer.valueOf(map.get("number").toString()) - Integer.valueOf(map.get("remainNumber").toString());
            redPacketMapper.updateRemainNumber(remainNumber,address,cipher);
            exchangeRateUtils.insertRedPacketRoll(coin,sendMoney,addressUid,number,remainNumber,address);
            //抢到的红包加入缓存，后边展示方
            List<Map<String,Object>> listRed = new ArrayList<>();
            boolean exis = redisUtils.exists(addressUid+cipher);
            if (!exis){
                listRed.add(map);
                redisUtils.setCacheListInMap(addressUid+cipher,listRed);
                jsonArray.add(map);
            }else {
                List<Map<String,Object>> mapListOld = redisUtils.getCacheListInMap(addressUid+cipher);
                for (Map<String,Object> redMap : mapListOld){
                    objMap = new HashMap<>();
                    objMap.put("invitationcode",redMap.get("invitationcode"));
                    objMap.put("createTime",redMap.get("createTime"));
                    objMap.put("remainNumber",redMap.get("remainNumber"));
                    objMap.put("number",redMap.get("number"));
                    objMap.put("value",redMap.get("value"));
                    objMap.put("coin",redMap.get("coin"));
                    objMap.put("address",redMap.get("address"));
                    objMap.put("accountUid",redMap.get("accountUid"));
                    objMap.put("sendMoney",redMap.get("sendMoney"));
                    listRed.add(objMap);
                    jsonArray.add(objMap);
                }
                listRed.add(map);
                redisUtils.setCacheListInMap(addressUid+cipher,listRed);
                jsonArray.add(map);
            }
        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");

    }

    public void redPacketRedis(String cipher,List<Map<String,Object>> list){
        redisUtils.setCacheListInMap(cipher,list);
        RedPacketMessage redPacketMessage = new RedPacketMessage(cipher,10);
        RedPacketQueue.getQueue().produce(redPacketMessage);
        System.out.println(redPacketMessage);
        runner.run(new DefaultApplicationArguments());
    }

    public List<Map<String,Object>> repacketMap(Double div,String coin,Integer number,String invitationcode,
                                          String addressUid,String address,String sendMoney){
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> map = null;
        for (int i = number; i > 0; i--) {
            map = new HashMap<>();
            map.put("value", div);
            map.put("coin", coin);
            map.put("number",number);
            map.put("invitationcode",invitationcode);
            map.put("addressUid",addressUid);
            map.put("address",address);
            list.add(map);
        }
        return list;
    }

//    @Transactional
//    public Object sendRedPacket(String coin, BigDecimal sendMoney, String address,
//                                Integer type, Integer number, String cipher, Integer jypassword) {
//        Map<String,Object> map = new HashMap<>();
//        String sub = "";
//        //String add = "";
//        JSONArray jsonArray = new JSONArray();
//        String moneyCoin = indexMapper.selectMoneyByCoin(coin, address);
//        //String sendCoin = indexMapper.selectMoneyByCoin(coin, toAddress);
//        Integer jYpassword = redPacketMapper.selectJYpassword(address);
//        String invitationcode = redPacketMapper.selectcInvitationcode(address);
//        if (sendMoney.compareTo(BigDecimal.ZERO) == -1) {
//            return Utils.toJSON("非法数量", jsonArray.toString(), "1");
//        }
//        if (!jypassword.equals(jYpassword)) {
//            return Utils.toJSON("交易密码错误，请重新输入", Utils.toJSONmap(), "3");
//        }
//        if (!(BigDecimalUtils.compare(sendMoney.toString(), moneyCoin))) {
//            //计算发送人剩余金额
//            sub = BigDecimalUtils.sub(moneyCoin, sendMoney.toString(), 8);
//            //计算收红包人金额
//            //add = BigDecimalUtils.add(sendMoney.toString(), sendCoin, 8);
//            indexMapper.updateCoinMoney(address, coin, sub);
//            //indexMapper.updateCoinMoney(toAddress, coin, add);
//        }else {
//            return Utils.toJSON("可用金额不足", jsonArray.toString(), "1");
//        }
//        exchangeRateUtils.insertRedPacket(coin,sendMoney,address,type,number,cipher);
//        map.put("invitationcode",invitationcode);
//        map.put("remainingSum",moneyCoin);
//        return Utils.toJSON("发送成功",map.toString(),"0");
//    }


//     for (Map<String,Object> cache : cacheListInMap){
//        map = new HashMap<>();
//        object = new JSONObject();
//        object.put("value",cache.get("value"));
//        object.put("fromAddress",cache.get("fromAddress"));
//        object.put("coin",cache.get("coin"));
//        System.out.println(object);
//    }
//    int size = cacheListInMap.size();
//                    System.out.println(size);
}
